﻿using System;
using System.Web.UI;
using Project.Model;
using Project.Common;
using System.Xml;
using System.Web.UI.WebControls;
using NHibernate.Criterion;
using System.Collections.Generic;

namespace Web
{
    /// <summary>
    /// 功能：编辑页面
    ///       (UserManager)
    /// 作者：luky
    /// 日期：2010-12-22
    /// </summary>
    public partial class UserManager_Edit : AdminPage
    {
        XmlDocument doc = new XmlDocument();
        protected void Page_Load(object sender, EventArgs e)
        {
            doc.Load(Server.MapPath("~/Area.xml"));

            SendSMSButton.Visible = base.IsSendSMS;

            if (!IsPostBack)
            {
                //此处添加需要绑定的控件
                base.BindEnum2WebControls(UserTypeDropDownList, typeof(EnumUserType), true, 0);
                base.BindEnum2WebControls(ProvinceDropDownList, typeof(EnumProvince), false, 0);
                base.BindEnum2WebControls(Dw_tradDropDownList, typeof(EnumDw_trad), false, 0);
                base.BindEnum2WebControls(Chsh_managementDropDownList, typeof(EnumChsh_management), false, 0);
                if (Chsh_managementDropDownList.Items.IndexOf(new ListItem(EnumChsh_management.请选择.ToString(), EnumChsh_management.请选择.ToString())) > -1)
                {
                    Chsh_managementDropDownList.Items.Remove(new ListItem(EnumChsh_management.请选择.ToString(), EnumChsh_management.请选择.ToString()));
                    Chsh_managementDropDownList.Items.Insert(0, new ListItem(EnumChsh_management.请选择.ToString(), ""));
                }

                #region 绑定省市下拉框
                //读取节点值
                XmlNodeList provinceNodeList = doc.SelectNodes("//address/province");
                foreach (XmlNode item in provinceNodeList)
                {
                    provincesDropDownList.Items.Add(new ListItem(item.Attributes["name"].Value, item.Attributes["name"].Value));
                }
                this.provincesDropDownList_SelectedIndexChanged(sender, e);
                this.Sz_addressDropDownList_SelectedIndexChanged(sender, e);
                #endregion

                // 编辑状态才显示附件
                FilesPanel.Visible = base.SID > 0;
                if (base.SID > 0)
                {
                    // 编辑状态
                    UserManager model = ManagerFactory.UserManagerManager.Get(this.SID);
                    if (model == null)
                    {
                        Alert("记录不存在!");
                        ExecJsAjax("window.close();", Page);
                        return;
                    }

                    // 绑定页面控件与对象的值
                    base.BindControlsValue(Master.FindControl("ContentPlaceHolder1").Controls, model, true);

                    // 以下添加页面控件自定义显示代码
                    this.provincesDropDownList_SelectedIndexChanged(sender, e);
                    if (Sz_addressDropDownList.Items.FindByValue(model.Szaddress) != null)
                        Sz_addressDropDownList.Items.FindByValue(model.Szaddress).Selected = true;
                    this.Sz_addressDropDownList_SelectedIndexChanged(sender, e);
                    if (X_addressDropDownList.Items.FindByValue(model.Xaddress) != null)
                        X_addressDropDownList.Items.FindByValue(model.Xaddress).Selected = true;

                    txt_sh.Text = !string.IsNullOrEmpty(model.Sh) && Validator.IsInt(model.Sh.Trim()) && Enum.IsDefined(typeof(EnumIsAudit), int.Parse(model.Sh.Trim())) ? Enum.Parse(typeof(EnumIsAudit), model.Sh).ToString() : EnumIsAudit.未审核.ToString();
                    AuditButton.Text = !string.IsNullOrEmpty(model.Sh) && model.Sh.Trim() == ((int)EnumIsAudit.已审核).ToString() ? "取消审核" : "审核";
                    txt_Zc_data.Text = model.Zcdata;

                    // 显示附件 只有申报单位才有此附件
                    FilesPanel.Visible = model.UserType == ((int)EnumUserType.申报单位).ToString();
                    if (FilesPanel.Visible)
                    {
                        //创建查询器
                        IList<ICriterion> queryList = new List<ICriterion>();
                        queryList.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserNameFj>(d => d.USERNAME), model.USERNAME));
                        IList<UserNameFj> list = ManagerFactory.UserNameFjManager.GetList(queryList);
                        FilesRepeater.DataSource = list;
                        FilesRepeater.DataBind();
                    }

                    // 只有审核之后才能重新发送短信
                    SendSMSButton.Visible = !string.IsNullOrEmpty(model.Sh) && model.Sh.Trim() == ((int)EnumIsAudit.已审核).ToString();

                }
                else
                {
                    // 新建
                    txt_Zc_data.Text = DateTime.Now.ToShortDateString();
                    AuditButton.Visible = false;
                }

                // 查看
                if (Request.Params["isenable"] != null)
                {
                    ClientScript.RegisterStartupScript(typeof(Page), "a", "<script>ChangeToLabel();</script>");
                }

            }

        }

        // 保存
        protected void saveButton_Click(object sender, System.EventArgs e)
        {
            if (IsValid)
            {
                UserManager model = new UserManager();

                try
                {
                    if (this.SID > 0)
                    {
                        // 更新
                        model = ManagerFactory.UserManagerManager.Get(this.SID);
                    }
                    else
                    {
                        // 新建
                    }

                    if (model == null)
                    {
                        Alert("记录不存在!");
                        ExecJsAjax("window.close();", Page);
                        return;
                    }

                    // 绑定页面控件与对象的值
                    model = base.BindControlsValue(Master.FindControl("ContentPlaceHolder1").Controls, model, false);

                    if (UserTypeDropDownList.SelectedValue == ((int)EnumUserType.受理中心).ToString()
                            || UserTypeDropDownList.SelectedValue == ((int)EnumUserType.市州科技局).ToString()
                            || UserTypeDropDownList.SelectedValue == ((int)EnumUserType.县区科技局).ToString()
                            
                        )
                    {
                        model.Chshmanagement = null;
                    }

                    if (this.SID > 0)
                    {
                        // 更新
                       
                        ManagerFactory.UserManagerManager.Update(model);
                      
                    }
                    else
                    {
                        // 新建
                        ManagerFactory.UserManagerManager.Save(model);
                    }
                    Alert("保存成功!");
                    ExecJsAjax("window.opener.searchRefresh();window.close();", Page);
                }
                catch (Exception ex)
                {
                    Alert(ex.Message);
                }
            }
        }
        // 审核
        protected void AuditButton_Click(object sender, System.EventArgs e)
        {
            if (IsValid)
            {
                UserManager model = new UserManager();

                try
                {
                    if (this.SID > 0)
                    {
                        // 更新
                       
                        model = ManagerFactory.UserManagerManager.Get(this.SID);
                        
                        if (model == null)
                        {
                            Alert("记录不存在!");
                            ExecJsAjax("window.close();", Page);
                            return;
                        }
                    }
                    else
                    {
                        // 新建
                    }

                    // 赋值
                    model.Sh = !string.IsNullOrEmpty(model.Sh) && model.Sh.Trim() == ((int)EnumIsAudit.已审核).ToString() ? ((int)EnumIsAudit.未审核).ToString() : ((int)EnumIsAudit.已审核).ToString();

                    if (this.SID > 0)
                    {
                        // 更新
                       
                        ManagerFactory.UserManagerManager.Update(model);
                       
                        // 审核成功 向用户发送短信:包含用户名和密码
                        // 获取用户手机号
                        if (model.Sh == ((int)EnumIsAudit.已审核).ToString() && base.IsSendSMS)
                        {
                            if (!Validator.IsMobile(model.Lxrtel))
                            {
                                Alert("'联系人手机'填写的不是有效的手机号码,短信发送失败!");
                            }
                            else
                            {
                                string content = "青海科技计划项目受理中心提示:您的帐号 " + model.USERNAME + " 已审核通过.密码是: " + model.UserPass + " 请注意保存.";
                                //SendSMS(model.Lxrtel, content);
                                XmlDocument doc = new XmlDocument();
                                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                                doc.AppendChild(dec);
                                //创建一个根节点（一级）
                                XmlElement root = doc.CreateElement("root");
                                doc.AppendChild(root);

                                XmlElement element = doc.CreateElement("authkeycode");
                                element.InnerText = "cWhreGpzeHh6anMzOWI3ZTM5YWY4ZGM3ZDJhNTI4ZTRhMDlhZThjNDE0ZA==";
                                root.AppendChild(element);
                                XmlElement element2 = doc.CreateElement("phsnumber");
                                element2.InnerText = model.Lxrtel;
                                root.AppendChild(element2);
                                XmlElement element3 = doc.CreateElement("smscontent");
                                element3.InnerText = content;
                                root.AppendChild(element3);
                                string resqult = doc.OuterXml;
                                //Console.Write(resqult);
                                //  doc.Save(Server.MapPath("data1.xml"));
                                // ServiceReference service = new ServiceReference(webservice);
                                WebReference.SmsInterfacesService SMS = new WebReference.SmsInterfacesService();
                                SMS.smsdata(resqult);
                                Alert("短信发送成功!");
                            }
                        }
                    }
                    else
                    {
                        // 新建
                        //ManagerFactory.UserManagerManager.Save(model);
                    }
                    Alert("保存成功!");
                    ExecJsAjax("window.opener.searchRefresh(); location=location", Page);
                }
                catch (Exception ex)
                {
                    Alert(ex.Message);
                }
            }
        }
        // 重新发送短信
        protected void SendSMSButton_Click(object sender, System.EventArgs e)
        {
            UserManager model = new UserManager();

            try
            {
                if (this.SID > 0)
                {
                    // 更新
                    model = ManagerFactory.UserManagerManager.Get(this.SID);

                    if (model == null)
                    {
                        Alert("记录不存在!");
                        ExecJsAjax("window.close();", Page);
                        return;
                    }
                }
                else
                {
                    // 新建
                }

                // 赋值
                //model.Sh = !string.IsNullOrEmpty(model.Sh) && model.Sh.Trim() == ((int)EnumIsAudit.已审核).ToString() ? ((int)EnumIsAudit.未审核).ToString() : ((int)EnumIsAudit.已审核).ToString();

                if (this.SID > 0)
                {
                    // 更新
                    //ManagerFactory.UserManagerManager.Update(model);

                    // 审核成功 向用户发送短信:包含用户名和密码
                    // 获取用户手机号
                    if (!string.IsNullOrEmpty(model.Sh) && model.Sh.Trim() == ((int)EnumIsAudit.已审核).ToString() && base.IsSendSMS)
                    {
                        if (!Validator.IsMobile(model.Lxrtel))
                        {
                            Alert("'联系人手机'填写的不是有效的手机号码,短信发送失败!");
                        }
                        else
                        {
                            string content = "青海科技计划项目受理中心提示:您的帐号是 " + model.USERNAME + " 密码是: " + model.UserPass + " 请注意保存.";
                            //SendSMS(model.Lxrtel, content);
                            XmlDocument doc = new XmlDocument();
                            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                            doc.AppendChild(dec);
                            //创建一个根节点（一级）
                            XmlElement root = doc.CreateElement("root");
                            doc.AppendChild(root);

                            XmlElement element = doc.CreateElement("authkeycode");
                            element.InnerText = "cWhreGpzeHh6anMzOWI3ZTM5YWY4ZGM3ZDJhNTI4ZTRhMDlhZThjNDE0ZA==";
                            root.AppendChild(element);
                            XmlElement element2 = doc.CreateElement("phsnumber");
                            element2.InnerText = model.Lxrtel;
                            root.AppendChild(element2);
                            XmlElement element3 = doc.CreateElement("smscontent");
                            element3.InnerText = content;
                            root.AppendChild(element3);
                            string resqult = doc.OuterXml;
                            //Console.Write(resqult);
                            //  doc.Save(Server.MapPath("data1.xml"));
                            // ServiceReference service = new ServiceReference(webservice);
                            WebReference.SmsInterfacesService SMS = new WebReference.SmsInterfacesService();
                            SMS.smsdata(resqult);
                            Alert("短信发送成功!");
                        }
                    }
                    else
                    {
                        Alert("审核之后才能发送短信");
                    }
                }
                else
                {
                    // 新建
                    //ManagerFactory.UserManagerManager.Save(model);
                }
                //Alert("保存成功!");
                ExecJsAjax("window.opener.searchRefresh(); location=location", Page);
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        protected void provincesDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindSz_addressDropDownList(provincesDropDownList.SelectedValue);
        }

        protected void Sz_addressDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindX_addressDropDownList(Sz_addressDropDownList.SelectedValue);
        }

        private void BindSz_addressDropDownList(string p)
        {
            Sz_addressDropDownList.Items.Clear();
            //读取节点值
            XmlNodeList provinceNodeList = doc.SelectNodes("//address/province[@name='" + p + "']/city");
            foreach (XmlNode item in provinceNodeList)
            {
                Sz_addressDropDownList.Items.Add(new ListItem(item.Attributes["name"].Value, item.Attributes["name"].Value));
            }
            Sz_addressDropDownList.ClearSelection();
        }

        private void BindX_addressDropDownList(string p)
        {
            X_addressDropDownList.Items.Clear();
            //读取节点值
            XmlNodeList provinceNodeList = doc.SelectNodes("//address/province[@name='" + provincesDropDownList.SelectedValue + "']/city[@name='" + p + "']/country");
            foreach (XmlNode item in provinceNodeList)
            {
                X_addressDropDownList.Items.Add(new ListItem(item.Attributes["name"].Value, item.Attributes["name"].Value));
            }
            X_addressDropDownList.ClearSelection();
        }

        #region 前端验证
        /// <summary>
        /// 当用户类别为:受理中心,推荐单位,的时候,下必须要选择 处事
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        protected void Chsh_managementCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (UserTypeDropDownList.SelectedValue == ((int)EnumUserType.受理中心).ToString()
                || UserTypeDropDownList.SelectedValue == ((int)EnumUserType.市州科技局).ToString()
                || UserTypeDropDownList.SelectedValue == ((int)EnumUserType.县区科技局).ToString()
            )
            {
                args.IsValid = true;
            }
            else
            {
                if (Chsh_managementDropDownList.SelectedIndex > 0)
                    args.IsValid = true;
                else
                    args.IsValid = false;
            }
        }
        /// <summary>
        /// 用户名必须唯一
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        protected void CheckUSERNAME(object source, ServerValidateEventArgs args)
        {
            //创建查询器
            IList<ICriterion> queryList = new List<ICriterion>();
            //传入条件
            queryList.Add(Restrictions.Eq(PropertyNameHelper.Resolve<UserManager>(d => d.USERNAME), txt_USERNAME.Text));
            IList<UserManager> list = ManagerFactory.UserManagerManager.GetList(queryList);
            args.IsValid = list.Count == 0;

            if (list.Count == 1)
            {
                // 编辑状态:检查 查找到的记录的Id是不是正在编辑的记录Id
                args.IsValid = list[0].Id == SID;
            }
        }

        #endregion
    }
}